package com.su.gulimall.seckill.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.su.common.to.mq.SeckillOrderTo;
import com.su.common.utils.R;
import com.su.common.vo.MemberRespVo;
import com.su.gulimall.seckill.feign.CouponFeignService;
import com.su.gulimall.seckill.feign.ProductFeignService;
import com.su.gulimall.seckill.interceptor.MyInterceptor;
import com.su.gulimall.seckill.service.SecKillService;
import com.su.gulimall.seckill.to.SecKillSkuRedisTo;
import com.su.gulimall.seckill.vo.SecKillSessionWithSkusVo;
import com.su.gulimall.seckill.vo.SkuInfoVo;
import org.redisson.api.RSemaphore;
import org.redisson.api.RedissonClient;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service
public class SecKillServiceImpl implements SecKillService {
    @Autowired
    CouponFeignService couponFeignService;
    @Autowired
    StringRedisTemplate redisTemplate;
    @Autowired
    ProductFeignService productFeignService;
    @Autowired
    RedissonClient redissonClient;
    @Autowired
    RabbitTemplate rabbitTemplate;

    private final String SESSIONS_CACHE_PREFIX = "seckill:session:";
    private final String SKUS_CACHE_PREFIX = "seckill:skus:";
    private final String SKU_STOCK_SEMAPHORE = "seckill:stock:";

    @Override
    public void uploadSecKillSku() {
        //1.扫描需要参加的活动的相关商品信息
        R session = couponFeignService.get3DaysSession();
        if (session.getCode() == 0) {
            //获取到需要上架的商品信息
            List<SecKillSessionWithSkusVo> data = (List<SecKillSessionWithSkusVo>) session.getData(new TypeReference<List<SecKillSessionWithSkusVo>>() {
            });
            //缓存到redis
            //1.缓存活动信息
            if(data!=null && data.size()>0)
            {
                saveSessionInfos(data);
                saveSessionSkuInfos(data);
            }

        }

    }
    //获取当前时间可以秒杀的商品信息
    //由于redis中存储了秒杀场次对应的时间范围，只要获取了当前时间，就可以进行匹配
    @Override
    public List<SecKillSkuRedisTo> getCurrentSecKillSkus() {
        //确定当前时间属于那个秒杀场次
        //距离1970年差值
        long time = new Date().getTime();
        //redis的key模糊匹配：先去秒杀的场次信息内获取到符合时间要求的key
        Set<String> keys = redisTemplate.keys("seckill:session:*");
        for (String key : keys) {
            String replace = key.replace("seckill:session:", "");
            String[] s = replace.split("_");
            Long start = Long.parseLong(s[0]);
            Long end = Long.parseLong(s[1]);
            //找到当前场的商品信息的key:一个list的sku集合
            if (time >= start && time <= end) {
                //拿到对应key的所有list数据；
                List<String> list = redisTemplate.opsForList().range(key, -100, 100);
                BoundHashOperations<String, String, String> ops = redisTemplate.boundHashOps(SKUS_CACHE_PREFIX);
                List<String> skuJsons = ops.multiGet(list);
                if (skuJsons != null && skuJsons.size() > 0) {
                    List<SecKillSkuRedisTo> collect = skuJsons.stream().map(skuJson -> {
                        SecKillSkuRedisTo secKillSkuRedisTo = JSON.parseObject(skuJson, SecKillSkuRedisTo.class);
                        return secKillSkuRedisTo;
                    }).collect(Collectors.toList());
                    return collect;
                }
                //跳出本次循环继续寻找
                break;
            }
        }
        //获取该秒杀场次需要的所有商品信息
        return null;
    }
    //获取秒杀详情
    @Override
    public SecKillSkuRedisTo getSkuSeckillInfo(Long skuId) {
        BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(SKUS_CACHE_PREFIX);
        Set<String> keys = hashOps.keys();
        if (keys != null && keys.size() > 0) {
            for (String key : keys) {
                String[] s = key.split("_");
                //比较内容是否一致
                if (s[1].equals(skuId.toString())) {
                    String json = hashOps.get(key);
                    SecKillSkuRedisTo redisTo = JSON.parseObject(json, SecKillSkuRedisTo.class);
                    long current = new Date().getTime();
                    //不在秒杀时间，随机码就置空，不予显示，此时不能进行秒杀
                    if (current < redisTo.getStartTime() || current > redisTo.getEndTime()) {
                        redisTo.setRandomCode(null);
                    }
                    return redisTo;
                }
            }
        }
        return null;
    }
    //请求不用直接去调用订单服务，
    //而是给消息队列发消息，并进行消峰处理
    @Override
    public String kill(String killId, String key, Integer num) {
        MemberRespVo memberRespVo = MyInterceptor.loginUser.get();
        //获取当前秒杀商品的详细信息
        BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(SKUS_CACHE_PREFIX);
        String s = hashOps.get(killId);
        if (!StringUtils.isEmpty(s)) {
            SecKillSkuRedisTo redisTo = JSON.parseObject(s, SecKillSkuRedisTo.class);
            //第一步，校验合法性
            //1.当前时间在秒杀时间内
            Long startTime = redisTo.getStartTime();
            Long endTime = redisTo.getEndTime();
            if (new Date().getTime() >= startTime && new Date().getTime() <= endTime) {
                //2.随机码和商品id是否匹配
                String randomCode = redisTo.getRandomCode();
                String skuId = redisTo.getPromotionSessionId() + "_" + redisTo.getSkuId();
                if (randomCode.equals(key) && skuId.equals(killId)) {
                    //3.购买数量是否合适
                    if (redisTo.getSeckillLimit().intValue() >= num) {
                        //4.用户是否购买过该商品；不能重复购买，幂等性
                        String redisKey = memberRespVo.getId() + "_" + skuId;
                        //当前key已经占位成功了，不能再次占位；
                        long ttl=endTime-new Date().getTime();
                        Boolean absent = redisTemplate.opsForValue().setIfAbsent(redisKey, num.toString(), ttl, TimeUnit.MILLISECONDS);
                        if(absent){
                            //这个人没买过
                            //第二步，对redis分布式信号量进行扣减；
                            RSemaphore semaphore = redissonClient.getSemaphore(SKU_STOCK_SEMAPHORE + randomCode);
                                //尝试信号量获取
                                boolean b = semaphore.tryAcquire(num);
                                if(b) {
                                    //秒杀成功，发送消息；异步处理
                                    String timeId = IdWorker.getTimeId();
                                    SeckillOrderTo orderTo = new SeckillOrderTo();
                                    //属性设置
                                    orderTo.setOrderSn(timeId);
                                    orderTo.setMemberId(memberRespVo.getId().toString());
                                    orderTo.setPromotionSessionId(redisTo.getPromotionSessionId());
                                    orderTo.setSkuId(redisTo.getSkuId());
                                    orderTo.setNum(num);
                                    orderTo.setSeckillPrice(redisTo.getSeckillPrice());
                                    rabbitTemplate.convertAndSend("order-event-exchange", "order.seckill.order", orderTo);
                                    return timeId;
                                }
                                else {
                                    return null;
                                }
                            }
                        else {
                            return null;
                        }
                    }
                } else {
                    return null;
                }
            } else {
                return null;
            }
        } else {
            return null;
        }
        return null;
    }
    //redis中保存某个场次信息：
    //key为:某个场次的开始时间到结束时间；
    //value为:该场对应的（商品所属的场次id-商品的skuId）
    private void saveSessionInfos(List<SecKillSessionWithSkusVo> sessions) {
        //对流中的方法需要加强理解；
        sessions.stream().forEach(session -> {
            Long startTime = session.getStartTime().getTime();
            Long endTime = session.getEndTime().getTime();
            String key = SESSIONS_CACHE_PREFIX + startTime + "_" + endTime;
            List<String> skuIds = session.getRelationskus().stream().map(
                    sku -> {
                        String id = sku.getPromotionSessionId().toString();
                        String skuId = sku.getSkuId().toString();
                        return id + "_" + skuId;
                    }).collect(Collectors.toList());
            //缓存活动信息(幂等性，保证没有该场次    才进行存储)
            if (!redisTemplate.hasKey(key)) {
                //以键值对作为信息进行存储；
                redisTemplate.opsForList().leftPushAll(key, skuIds);
            }
        });

    }

    //redis中保存该场次的商品详细信息：k:商品id  v：一个json字符串（保存详细信息）
    private void saveSessionSkuInfos(List<SecKillSessionWithSkusVo> sessions) {
        //循环遍历
        sessions.stream().forEach(session -> {
            //准备hash操作
            BoundHashOperations<String, Object, Object> operations = redisTemplate.boundHashOps(SKUS_CACHE_PREFIX);
            session.getRelationskus().stream().forEach(sku -> {
                String token = UUID.randomUUID().toString().replace("-", "");
                //缓存商品信息(该场次的id+该商品的skuid)
                if (!operations.hasKey(sku.getPromotionSessionId().toString() + "_" + sku.getSkuId().toString())) {
                    SecKillSkuRedisTo skuRedisTo = new SecKillSkuRedisTo();
                    //1.基本信息（）
                    R r = productFeignService.info(sku.getSkuId());
                    if (r.getCode() == 0) {
                        SkuInfoVo skuInfo = (SkuInfoVo) r.getData("skuInfo", new TypeReference<SkuInfoVo>() {
                        });
                        skuRedisTo.setSkuInfoVo(skuInfo);
                    }
                    //2.sku的秒杀信息（从优惠服务中已经查询出来）
                    BeanUtils.copyProperties(sku, skuRedisTo);
                    //3.sku的时间信息（当前活动的时间即为所有时间）
                    skuRedisTo.setStartTime(session.getStartTime().getTime());
                    skuRedisTo.setEndTime(session.getEndTime().getTime());
                    //4.随机的商品码（随机码在秒杀开始时才进行暴露，从而防止链接暴露引起的恶意请求）；
                    skuRedisTo.setRandomCode(token);
                    //字符串化
                    String s = JSON.toJSONString(skuRedisTo);
                    operations.put(sku.getPromotionSessionId().toString() + "_" + sku.getSkuId().toString(), s);
                    //5.分布式信号量的设置，
                    //用于扣减库存,
                    //只有先达到的请求才可以扣减，其余请求到这均被锁（达到了一个限流的目的）
                    RSemaphore semaphore = redissonClient.getSemaphore(SKU_STOCK_SEMAPHORE + token);
                    semaphore.trySetPermits(sku.getSeckillCount());
                }
            });
        });

    }

}
